package com.superfish.cutieshop.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.superfish.cutieshop.been.Red;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通用的工具类
 *
 * @author JackWu
 */
public class CommonUtil {
    private CommonUtil() {
    }

    // private static final double PI = Math.PI;
    private static final double EARTH_RADIUS = 6378137.0;

    public enum NetWorkState {
        WIFI, MOBILE, NONE;
    }

    /**
     * 获取当前的网络状态
     *
     * @return
     */
    public static NetWorkState getConnectState(Context mContext) {
        ConnectivityManager manager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        manager.getActiveNetworkInfo();
        State wifiState = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                .getState();
        State mobileState = manager.getNetworkInfo(
                ConnectivityManager.TYPE_MOBILE).getState();
        if (wifiState != null && mobileState != null
                && State.CONNECTED != wifiState
                && State.CONNECTED == mobileState) {
            return NetWorkState.MOBILE;
        } else if (wifiState != null && mobileState != null
                && State.CONNECTED != wifiState
                && State.CONNECTED != mobileState) {
            return NetWorkState.NONE;
        } else if (wifiState != null && State.CONNECTED == wifiState) {
            return NetWorkState.WIFI;
        }
        return NetWorkState.NONE;
    }

    /**
     * 显示键盘
     *
     * @param view
     */
    public static void showKeyboard(View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        InputMethodManager inputManager = (InputMethodManager) view
                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(view, 0);
    }

    /**
     * 隐藏键盘
     *
     * @param view
     */
    public static void hideKeyboard(View view) {
        ((InputMethodManager) view.getContext().getSystemService(
                Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                view.getWindowToken(), 0);
    }

    /**
     * 获取当前程序的versionCode
     *
     * @return versionCode
     */
    public static int getClientVersionCode(Context ctx) throws Exception {
        PackageManager packageManager = ctx.getPackageManager();
        PackageInfo packInfo = packageManager.getPackageInfo(
                ctx.getPackageName(), 0);
        return packInfo.versionCode;
    }

    /**
     * 获取当前程序的versionName
     *
     * @return versionName
     */
    public static String getClientVersionName(Context ctx) throws Exception {
        PackageManager packageManager = ctx.getPackageManager();
        PackageInfo packInfo = packageManager.getPackageInfo(
                ctx.getPackageName(), 0);
        return packInfo.versionName;
    }

    /**
     * 安装apk
     *
     * @param file *.apk文件
     */
    public static void installApk(File file, Context ctx) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        ctx.startActivity(intent);
    }

    /**
     * 获取当前网络状态
     *
     * @return true 有网
     */
    public static boolean getNetWorkStates(Context ctx) {
        ConnectivityManager manager = (ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    /**
     * 获取屏幕宽度
     **/
    public static int getWindowWidth(Activity act) {
        DisplayMetrics dm = new DisplayMetrics();
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @param act
     * @return
     */
    public static int getWindowHeight(Activity act) {
        DisplayMetrics dm = new DisplayMetrics();
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /**
     * 将内容复制到剪贴板
     *
     * @param context
     * @param text
     * @method
     */
    public static void saveTextToClipBoard(Context context, CharSequence text) {
        ClipboardManager cmb = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(text);
    }

    /**
     * 四舍五入
     **/
    public static String halfFormat(String str) {
        DecimalFormat df = new DecimalFormat("###,##0.00");
        String result = df.format(Double.parseDouble(str));
        return result;
    }

    /**
     * 判断一个字符串是否为整数
     **/
    public static boolean isInt(String str) {
        Pattern pattern = Pattern.compile("^\\d+$|-\\d+$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches())
            return false;
        return true;
    }

    /**
     * 判断字符串是否为小数
     **/
    public static boolean isDouble(String str) {
        Pattern pattern = Pattern.compile("\\d+\\.\\d+$|-\\d+\\.\\d+$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches())
            return false;
        return true;
    }

    /**
     * MD5加密
     *
     * @return
     * @method
     */
    public static String MD5(String content) {
        if (TextUtils.isEmpty(content)) {
            return "";
        }
        StringBuilder sb = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] result = digest.digest(content.getBytes());
            sb = new StringBuilder();
            for (byte b : result) {
                String hexString = Integer.toHexString(b & 0xFF);
                if (hexString.length() == 1) {
                    sb.append("0" + hexString);// 0~F
                } else {
                    sb.append(hexString);
                }
            }
        } catch (NoSuchAlgorithmException e) {
            return content;
        }
        return sb.toString();
    }

    /**
     * base64解码
     **/
    public static String base64decode(String base64str) {
        if (TextUtils.isEmpty(base64str)) {
            return base64str;
        }
        byte[] bytes = Base64.decode(base64str.getBytes(), Base64.DEFAULT);
        return new String(bytes);
    }

    /**
     * base64加密
     **/
    public static String encodeToString(String base64str) {
        if (TextUtils.isEmpty(base64str)) {
            return base64str;
        }
        return Base64.encodeToString(base64str.getBytes(), Base64.DEFAULT);
    }

    /**
     * 计算两个经纬度之间的距离
     **/
    public static double getDistance(double longitude1, double latitude1,
                                     double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 获取设备的唯一标示
     **/
    public static String getDeviceId(Context context) {
        // 优先设备号
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imei = tm.getDeviceId();
        if (!TextUtils.isEmpty(imei)) {
            return imei;
        }
        // wifi mac地址
        WifiManager wifi = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String wifiMac = info.getMacAddress();
        if (!TextUtils.isEmpty(wifiMac)) {
            return wifiMac;
        }

        // 手机序列号
        String sn = tm.getSimSerialNumber();
        if (!TextUtils.isEmpty(sn)) {
            return sn;
        }
        // 如果都没有则 生成一个uuid
        return UUID.randomUUID().toString();
    }

    /**
     * 拨打电话 -- 直接调转到拨号界面
     *
     * @param number
     */
    public static void callPhone(String number, Context context) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + number);
        intent.setData(data);
        context.startActivity(intent);
    }

    /**
     * 开启QQ聊天界面
     *
     * @param act
     * @param qq
     */
    public static void openQQChat(Activity act, String qq) {
        String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq
                + "&version=1";
        act.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

//    /**
//     * 改变推送状态
//     * @param context
//     */
//    public static void changeNotify(Context context) {
//        boolean isNotify = PersistTool.getBoolean(BaseConfig.ShareKey.NOTIFY_SWITCH, true);
//        if (!isNotify) {
//            PushAgent.getInstance(context).enable();
//        } else {
////            PushAgent.getInstance(context).setNoDisturbMode(0, 0, 23, 0);
//            PushAgent.getInstance(context).disable();
//        }
//    }

    public static void saveRed(Context context, boolean isShow) {
        DbUtils db = DbUtils.create(context);
        try {
            db.deleteAll(Red.class);
            Red red = new Red();
            red.isShow = isShow;
            db.save(red);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public static boolean isShowRed(Context context) {
        DbUtils db = DbUtils.create(context);
        try {
            Red red = db.findFirst(Red.class);
            if (red != null) {
                return red.isShow;
            } else {
                return false;
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断应用是否在系统中存在
     * @param context
     * @param pageName
     * @return
     */
    public static boolean isApkExist(Context context, String pageName) {
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(
                    pageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        } catch (Exception e) {
            return false;
        }

    }
}
